<template>
  <div class="feedback-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>反馈管理</span>
          <div class="search-container">
            <el-input
              v-model="searchContent"
              placeholder="搜索内容"
              style="width: 200px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select 
              v-model="searchStatus" 
              placeholder="状态" 
              style="width: 120px; margin-right: 10px"
              clearable
              @change="handleSearch"
            >
              <el-option label="未处理" :value="0" />
              <el-option label="已处理" :value="1" />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <el-table :data="feedbacks" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户" width="120">
          <template #default="scope">
            {{ scope.row.username || '未知用户' }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.images"
              :src="getImageUrl(scope.row.images)"
              :preview-src-list="[getImageUrl(scope.row.images)]"
              style="width: 50px; height: 50px; object-fit: cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="reply" label="回复内容" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
              {{ scope.row.status === 1 ? '已处理' : '未处理' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleReply(scope.row)">回复</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复/查看对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'reply' ? '回复反馈' : '查看反馈'"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="内容">
          <el-input type="textarea" v-model="form.content" :rows="4" disabled />
        </el-form-item>
        <el-form-item label="图片" v-if="form.images">
          <el-image
            :src="getImageUrl(form.images)"
            :preview-src-list="[getImageUrl(form.images)]"
            style="max-width: 100%; max-height: 300px"
          />
        </el-form-item>
        <el-form-item label="回复" prop="reply" v-if="dialogType === 'reply'">
          <el-input type="textarea" v-model="form.reply" :rows="4" />
        </el-form-item>
        <template v-if="dialogType === 'view' && form.reply">
          <el-form-item label="回复">
            <el-input type="textarea" v-model="form.reply" :rows="4" disabled />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            v-if="dialogType === 'reply'" 
            type="primary" 
            @click="handleSubmit"
          >
            提交回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/dateUtil'

const loading = ref(false)
const feedbacks = ref([])
const dialogVisible = ref(false)
const dialogType = ref('view')
const formRef = ref(null)
const searchContent = ref('')
const searchStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const form = reactive({
  id: '',
  content: '',
  reply: '',
  status: ''
})

const rules = {
  reply: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

const formatDate = (date) => {
  return formatDateTime(date)
}

const loadFeedbacks = async () => {
  try {
    loading.value = true
    const res = await request.get('/admin/feedbacks', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        content: searchContent.value,
        status: searchStatus.value
      }
    })
    if (res.code === 200) {
      feedbacks.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('Failed to load feedbacks:', error)
    ElMessage.error('加载反馈列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadFeedbacks()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadFeedbacks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadFeedbacks()
}

const handleReply = (row) => {
  dialogType.value = 'reply'
  dialogVisible.value = true
  Object.assign(form, row)
}

const handleView = (row) => {
  dialogType.value = 'view'
  dialogVisible.value = true
  Object.assign(form, row)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await request.put(`/admin/feedbacks/${form.id}/reply`, {
          reply: form.reply
        })
        ElMessage.success('回复成功')
        dialogVisible.value = false
        loadFeedbacks()
      } catch (error) {
        console.error('Failed to reply feedback:', error)
        ElMessage.error('回复失败')
      }
    }
  })
}

const handleDelete = async (row) => {
  try {
    await request.delete(`/admin/feedbacks/${row.id}`)
    ElMessage.success('留言删除成功')
    loadFeedbacks()
  } catch (error) {
    console.error('删除留言失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

const getImageUrl = (path) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  return `http://localhost:8080/api${path}`
}

loadFeedbacks()
</script>

<style scoped>
.feedback-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
</style> 